package com.dries.chat.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/7/8 14:21
 */
public class WSServerInitialzer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();

        // 基于http 使用http编解码器
        pipeline.addLast(new HttpServerCodec());
        // 以块的方式写，添加ChunkedWriteHandler处理器
        pipeline.addLast(new ChunkedWriteHandler());
        // http数据在传输过程中分段，HttpObjectAggregator将多个段聚合
        pipeline.addLast(new HttpObjectAggregator(1024*64));
        // WebSocketServerProtocolHandler核心功能是将http协议升级为ws协议，保持长连接
        pipeline.addLast(new WebSocketServerProtocolHandler("/websocket"));

        // 针对客户端，如果在1分钟时没有向服务端发送读写心跳（ALL），则主动断开
        // 如果是读空闲或者写空闲，不处理
        pipeline.addLast(new IdleStateHandler(20,40,60));
        // 增加心跳支持 start
        pipeline.addLast(new HeartBeatHandler());

        // 自定义handler,处理业务逻辑
        pipeline.addLast(new WSServerHandler());


    }
}
